package com.newlink.building.common_base.ext

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken

/**
 * @Author: Jake
 * @Date: 2024-10-15
 * @Description:
 */
inline fun <reified T> String.toBean(includeNulls: Boolean = true): T {
    return gson(includeNulls).fromJson(this, object : TypeToken<T>() {}.type)
}

inline fun <reified T> String.toBeanOrNull(includeNulls: Boolean = true): T? =
    runCatching { toBean<T>() }.onFailure { it.printStackTrace() }.getOrNull()


fun gson(includeNulls: Boolean): Gson = if (includeNulls) GSON else GSON_NO_NULLS


private val GSON by lazy {
    GsonBuilder().create()
}

private val GSON_NO_NULLS by lazy {
    GsonBuilder().serializeNulls().create()
}

private val GSON_PRETTY by lazy {
    GsonBuilder().setPrettyPrinting().create()
}

fun Any.toJson(includeNulls: Boolean = true): String {
    return gson(includeNulls).toJson(this)
}